package com.fsts.util;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * 文件发送类
 * 
 * 
 * @version 1.0
 * @since JDK1.6(建议)
 */
public class SendFile {
	public void sendFile(String destIp, int port, String filePath) {
		DataOutputStream out = null;
		DataInputStream in = null;
		Socket socket = null;
		try {
			System.out.println("请求对主机址......");
			socket = new Socket(destIp, port);
			System.out.println("连接对方主机成功>>>>>");
			out = new DataOutputStream(socket.getOutputStream());
			in = new DataInputStream(socket.getInputStream());
			System.out.println("向对方发送信息......");
			out.writeUTF("我最近还不错");
			System.out.println("向对方发送信息成功>>>>>");
			System.out.println("接受对方返回信息>>>>");
			System.out.println("返回信息：" + in.readUTF());
			System.out.println("请求发送文件>>>>>>");
			File file = new File(filePath);
			System.out.println("文件总长度：" + file.length());
			byte[] b = new byte[1000000];
			FileInputStream fileInputStream = new FileInputStream(file);
			out.writeUTF(file.getName());
			out.writeLong(file.length());
			while (true) {
				// 返回读入的字节长度，其实就是b数组的长度
				int read = fileInputStream.read(b);
				// 都完以后返回-1
				if (read == -1) {
					break;
				}
				// 将指定字节数组中从偏移量 0 开始的 read 个字节写入基础输出流。
				out.write(b, 0, read);
			}
			System.out.println("发送完成>>>>>");
			out.flush();
		} catch (UnknownHostException e) {
			e.printStackTrace();
			System.err.println("接收方连接错误...");
		} catch (IOException e) {
			e.printStackTrace();
			System.err.println("读取文件错误...");
		} finally {
			try {
				out.close();
				in.close();
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}

	}
}
